#include <stdio.h>
#include <stdlib.h>

typedef struct Seq_Stack Seq_Stack_t;
typedef struct Seq_Stack* pSeq_Stack_t;

/*
栈-先进后出
*/

//栈
struct Seq_Stack{
    //顺序栈入口
    int *data;
    //顺序栈大小
    int size ;
    //栈元素的下标
    int top;
};

pSeq_Stack_t Init_Seq_Stack( int size )
{ 
    pSeq_Stack_t pseq_stack = ( pSeq_Stack_t )malloc( sizeof( Seq_Stack_t ) );
    if( NULL == pseq_stack )
    {
        printf( "malloc error" );
        return NULL;
    }
    
    pseq_stack->data = ( int * )malloc( size * sizeof( int ) );
    pseq_stack->size = size;
    pseq_stack->top = -1;
}

void Push_Seq_Stack( pSeq_Stack_t pseq_stack,int data )
{
    //判断栈是否已满
    if( pseq_stack->top == pseq_stack->size - 1 )
    {
        printf( "stack is full\n" );
        return;
    }
    //将元素压入栈
    pseq_stack->data[++pseq_stack->top] = data;
    
}

int Pop_Seq_Stack( pSeq_Stack_t pseq_stack )
{
    //判断栈是否为空
    if( pseq_stack->top == -1 )
    {
        printf( "stack is empty\n" );
        return -1;
    }
    //将元素弹出栈
    int data = pseq_stack->data[pseq_stack->top--];
    return data;  
}

void Print_Seq_Stack( pSeq_Stack_t pseq_stack )
{
    if( pseq_stack->top == -1 )
    {
        printf( "stack is empty\n" );
        return;
    }
    printf("栈顶->");
    for(int i = 0; i <= pseq_stack->top; i++)
    {
        printf("%d ",pseq_stack->data[i]);
    }
    printf("<-栈底\n");
}

void Destory_Seq_Stack(pSeq_Stack_t pseq_stack)
{
    free( pseq_stack->data );
    free( pseq_stack );
    printf( "销毁成功\n" );
} 

int main(){
    pSeq_Stack_t pseq_stack = Init_Seq_Stack(6);
    if( pseq_stack == NULL )
    {
        perror( "Init_Seq_Stack error" );
        return -1;
    }
    Push_Seq_Stack( pseq_stack, 1 );
    Push_Seq_Stack( pseq_stack, 2 );
    Push_Seq_Stack( pseq_stack, 3 );
    Push_Seq_Stack( pseq_stack, 4 );
    Push_Seq_Stack( pseq_stack, 5 );

    while( pseq_stack->top != -1 )
    {
        printf( "Pop_Seq_Stack: %d\n", Pop_Seq_Stack( pseq_stack ) );
    }

    #if 1
    Print_Seq_Stack( pseq_stack );
    Pop_Seq_Stack( pseq_stack );
    Pop_Seq_Stack( pseq_stack );
    Pop_Seq_Stack( pseq_stack );
    Pop_Seq_Stack( pseq_stack );
    Pop_Seq_Stack( pseq_stack );
    Pop_Seq_Stack( pseq_stack );
    Push_Seq_Stack( pseq_stack, 6 );
    Print_Seq_Stack( pseq_stack );
    #endif


    Destory_Seq_Stack( pseq_stack );


    return 0;
}